<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Movie;
use App\Crawlers\MovieInfoCrawler;
use App\Models\MovieBaseInfo;

class CrawlerMovieJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(MovieInfoCrawler $crawler)
    {
        $result = $crawler->get($this->id);
        if (!$result) {
            $mb = MovieBaseInfo::where('douban_id', $this->id)->first();
            $mb->increment('crawler_count');// update(['is_crawler' => true]);
            return;
        }
        if ($movie = Movie::where('douban_id', $this->id)->first()) {
            $movie->fill($result);
        } else {
            $movie = new Movie;
            $movie->fill($result);
        }
        $movie->save();
        // 处理 演员 编剧 导演数据
        $movie->updateActors( $result['actors']);
        $movie->updateDirectors( $result['directors']);
        $movie->updateAuthors( $result['authors']);
        $movie->updateCategories( $result['categories']);
        // 更新 列表状态
        $mb = MovieBaseInfo::where('douban_id', $this->id)->first();
        $mb->update(['is_crawler' => true]);
    }
}
